package sv.ues.fia.adminperfildocentes;

import java.util.ArrayList;
import java.util.HashMap;

import sv.ues.fia.adminperfildocentes.adapter.ListAdapter;
import sv.ues.fia.adminperfildocentes.model.Formacion;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ListarFormacionesActivity extends Activity {


	ListAdapter mAdapter;
	ControlDB BDhelper;
	ListView lvFormacion;
	EditText editbuscar;
	String values[] = null;
	int textlength =0;
	ArrayList<HashMap<String, String>> array_sort = new ArrayList<HashMap<String, String>>();
	ArrayList<HashMap<String, String>> listarFormacion = new ArrayList<HashMap<String, String>>();
	//creamos el context menu
	final int CONTEXT_MENU_VER =1;
	final int CONTEXT_MENU_UPDATE =2;
	final int CONTEXT_MENU_ELIMINAR = 3;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listar_formaciones);
		BDhelper = new ControlDB(this);
		
		listarFormacion = BDhelper.listarFormacion();
	
		// Instanciamos los elementos
		lvFormacion = (ListView) findViewById(R.id.listviewformacion);
		
		mAdapter = new ListAdapter(this,listarFormacion);
                
		// Establecemos el adapter
		lvFormacion.setAdapter(mAdapter);
			
		// registramos el menu
		registerForContextMenu(lvFormacion);
		
		//filtrado con el edit
		editbuscar = (EditText) findViewById(R.id.editBusqueda);
		editbuscar.addTextChangedListener(new TextWatcher() {
			 @Override
		    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
		        // When user changed the Text
				 textlength = editbuscar.getText().length();
	                array_sort.clear();
	                
	                for (int i = 0; i < listarFormacion.size(); i++) {
	                	String itemnom = mAdapter.getItem(i);
	                	String itemid = String.valueOf(mAdapter.getItemId(i));
	                	int longitud = itemnom.length();
	                    if (textlength <= longitud) {
	                        if (editbuscar.getText().toString().equalsIgnoreCase((String) itemnom.subSequence(0, textlength))) {
	                        	HashMap<String, String> actual = new HashMap<String, String>();
	                        	actual.put("id", itemid);
	                			actual.put("nombre", itemnom);
	                            array_sort.add(actual);
	                        }
	                    }
	                }
	                 
	                lvFormacion.setAdapter(new  ListAdapter(ListarFormacionesActivity.this, array_sort));
		    }
		    @Override
		    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
		            int arg3) { }
		    @Override
		    public void afterTextChanged(Editable arg0) {}
		  });
		
		//evento click de cada item
		lvFormacion.setOnItemClickListener(new OnItemClickListener() {
      
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				Intent intent = new Intent(getApplicationContext(), ConsultarFormacionActivity.class);
				long id= arg0.getAdapter().getItemId(position);
					
			    intent.putExtra("idFormacion", id);
			  
				startActivity(intent);  
			}
        });
		
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.optiones_menu, menu);
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.opt_agregar:
			Toast.makeText(this, R.string.nuevo, Toast.LENGTH_SHORT).show();
			Intent intentinsert = new Intent(getApplicationContext(), InsertarFormacionActivity.class);
			startActivity(intentinsert);
			return (true);
		case R.id.opt_ayuda:
			
AlertDialog alertDialog2 = new AlertDialog.Builder(this).create();
			
		    // Setting Dialog Title
		    alertDialog2.setTitle(getString(R.string.ayuda));
		
		    // Setting Dialog Message
		    alertDialog2.setMessage(getString(R.string.msjAyudaLista));
		
		    // Setting Icon to Dialog
		    alertDialog2.setIcon(R.drawable.ic_menu_help);
		
		    // Setting OK Button
		    alertDialog2.setButton("OK", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		           
		            }
		    });
		
		    // Showing Alert Message
		    alertDialog2.show();
			return (true);
		case R.id.opt_inicio:
			
			Intent intent = new Intent(this, AdministradorActivity.class);
			startActivity(intent);
			return (true);
		
		}
		return (super.onOptionsItemSelected(item));
	}
	

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) 
	{          
		menu.add(Menu.NONE, CONTEXT_MENU_VER, Menu.NONE, R.string.detalle);
		menu.add(Menu.NONE, CONTEXT_MENU_UPDATE, Menu.NONE, R.string.modificar);
		menu.add(Menu.NONE, CONTEXT_MENU_ELIMINAR, Menu.NONE, R.string.eliminar);
		menu.setHeaderTitle(R.string.acciones);
		menu.setHeaderIcon(R.drawable.arrow);
	}
	
	//eventos para los item del context menu
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		int index = info.position;
		long id= lvFormacion.getAdapter().getItemId(index);
		String idStr;
		idStr = String.valueOf(id);
		
		switch (item.getItemId()) 
		{
			case CONTEXT_MENU_VER:
				Intent intentDetalle = new Intent(getApplicationContext(), ConsultarFormacionActivity.class);
				
				intentDetalle.putExtra("idFormacion", id);
				startActivity(intentDetalle);  
				return(true);
				
			case CONTEXT_MENU_UPDATE:
				Intent intentActualizar = new Intent(this, ActualizarFormacionActivity.class);
				intentActualizar.putExtra("idFormacion", idStr);
				startActivity(intentActualizar);  
			       
				return(true);    
			case CONTEXT_MENU_ELIMINAR:
				eliminarFormacion(idStr);
 			       
				return(true);   
		
		}
		return super.onOptionsItemSelected(item);
	}	
	
	public void llamarInsertarFormacion(View v)
	{
		Intent intent = new Intent(getApplicationContext(), InsertarFormacionActivity.class);
		startActivity(intent);
	}
	
	public void eliminarFormacion(final String id)
	{
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				this);
 
			// set title
			alertDialogBuilder.setTitle(R.string.eliminareg);
 
			// set dialog message
			alertDialogBuilder
				.setMessage(R.string.msjeliminar)
				.setCancelable(false)
				.setPositiveButton(R.string.si,new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int idOption) {
						
						Formacion formacion = new Formacion();
						formacion.setIdformacion(Integer.parseInt(id));
						BDhelper.abrir();
						int accion = BDhelper.eliminarFormacion(formacion);
						BDhelper.cerrar();
						if (accion == -1 || accion == 0) {
							Toast.makeText(getBaseContext(), R.string.erroreliminar, Toast.LENGTH_SHORT).show();
							Intent intent1 = new Intent(getApplicationContext(), ListarFormacionesActivity.class);
							startActivity(intent1);
						} else {
							Toast.makeText(getBaseContext(), R.string.okeliminar, Toast.LENGTH_SHORT).show();
							Intent intent2 = new Intent(getApplicationContext(), ListarFormacionesActivity.class);
							startActivity(intent2);
						}
					
						
					}
				  })
				.setNegativeButton(R.string.no,new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						// if this button is clicked, just close
						// the dialog box and do nothing
						dialog.cancel();
					}
				});
 
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();


	}
	
}
